package com.sczmgk.hotline_pzh.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lidroid.xutils.BitmapUtils;
import com.sczmgk.hotline_pzh.MyApp;
import com.sczmgk.hotline_pzh.R;
import com.sczmgk.hotline_pzh.base.RefreshAndLoadMoreBaseActivity;
import com.sczmgk.hotline_pzh.callback.SimplePaserJsonCallback;
import com.sczmgk.hotline_pzh.constants.Constants;
import com.sczmgk.hotline_pzh.dialog.DialogFactory;
import com.sczmgk.hotline_pzh.entity.BaseEntity;
import com.sczmgk.hotline_pzh.entity.WorkInfo;
import com.sczmgk.hotline_pzh.httputils.MyHttp;
import com.sczmgk.hotline_pzh.sp.CacheUtils;
import com.sczmgk.hotline_pzh.utils.CommonUtils;
import com.sczmgk.hotline_pzh.view.NoDoubleItemClickListener;
import com.sczmgk.hotline_pzh.view.RefreshListView;
import com.shizhefei.view.indicator.Indicator;
import com.shizhefei.view.indicator.ScrollIndicatorView;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2016/12/8 0008.
 */
public class MyWorkActivity extends RefreshAndLoadMoreBaseActivity<WorkInfo> {

    /*发送的消息*/
    private static final int WORK_INFO = 310;

    /*指示器控件*/
    private ScrollIndicatorView mIndicator;

    /*空的图片的控件*/
    private LinearLayout mLayoutEmpty;

    /*审核完成与待审核*/
    private static final int AUDIT_COMPLETED = 8;
    private static final int TO_AUDIT = 7;

    private MyAdapter adapter;
    private BitmapUtils bitmapUtils;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_work);

        bitmapUtils = new BitmapUtils(getApplicationContext()) ;
		bitmapUtils.configDefaultLoadFailedImage(R.drawable.complain_default_pic);
        bitmapUtils.configDefaultBitmapMaxSize(200,200);

        setHeader();

        initView();

        initData();

        setListener();
    }

    /**
     * 设置头
     */
    private void setHeader() {
        setTitle(R.string.my_work);
        setLeftBtnVisibility(View.VISIBLE);
    }

    /**
     * 初始化控件
     */
    private void initView() {

        //消息条目
        mListView = (RefreshListView) findViewById(R.id.lv_my_work);

        //指示器控件
        mIndicator = (ScrollIndicatorView) findViewById(R.id.siv_my_work);

        //空的图片的控件
        mLayoutEmpty = (LinearLayout) findViewById(R.id.ll_work_empty);

        //设置Indicator指示器
        mIndicator.setBackgroundResource(R.color.white);
        String[] indicatorTitle = getResources().getStringArray(R.array.my_work_indicator);
        CommonUtils.setIndector(mIndicator, indicatorTitle, this);

    }

    /**
     * 初始化数据
     */
    private void initData() {

        //设置adapter
        adapter = new MyAdapter();
        mListView.setAdapter(adapter);

        //初始化访问我的消息数据
        mIndicator.setCurrentItem(0);
    }

    /**
     * 设置监听
     */
    @Override
    public void setListener() {
        super.setListener();

        //ListView条目点击事件
        mListView.setOnItemClickListener(new NoDoubleItemClickListener() {

            @Override
            public void NoDoubleItemClickListener(AdapterView<?> parent, View view, int i, long id) {
                int position = i - 1;
                final WorkInfo info = lists.get(position);
                if (info.isread == 0) {
                    lists.get(position).isread = 1;
                    //发送我的消息的已读消息到服务器
                    postMessageData(info.msgid);
                }

                //跳转到消息界面
                Intent workIntent = new Intent(MyWorkActivity.this, WorkDetailActivity.class);
                workIntent.putExtra(Constants.WORK_DETAIL, lists.get(position).id);
                workIntent.putExtra(Constants.WORK_TYPE_DETAIL, lists.get(position).status);
                startActivity(workIntent);
            }
        });

//        我的工作条目的长点击事件
//        mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
//            @Override
//            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long l) {
//
//                showDeleteDialog(position);
//
//                return true ;
//            }
//        });

        //设置指示器的监听
        mIndicator.setOnItemSelectListener(new Indicator.OnItemSelectedListener() {

            @Override
            public void onItemSelected(View view, int itemPosition, int i1) {

                if (mLayoutEmpty.getVisibility() == View.VISIBLE) {
                    mLayoutEmpty.setVisibility(View.GONE);
                }

                if (lists.size() > 0) {
                    lists.clear();
                    mHandler.sendEmptyMessage(REFRESH_LIST);
                }

                loadData(1, "", LOAD_NORMAL);

            }
        });

    }

    @Override
    public Map<String, Object> getRequestData(int page, String keyword) {

        int userid = CacheUtils.getIntData(MyWorkActivity.this, Constants.LOGIN_UID, 0);

        Map<String, Object> infos = new HashMap<>();
        infos.put("querystatus", mIndicator.getCurrentItem());
        infos.put("imei", MyApp.imei);
        infos.put("page", page);
        infos.put("userid", userid);

        return infos;
    }

    @Override
    public String getRquestUrl() {
        return Constants.BASE_URL + Constants.GET_MY_WORK_URL;
    }

    @Override
    public int getListType() {
        return LIST_TYPE_UP_LOAD_MORE;
    }

    /**
     * 点击条目后传递已读消息id到服务器
     */
    private void postMessageData(int msgid) {

        Map<String, Object> infos = new HashMap<>();
        infos.put("msgid", msgid);

        MyHttp.requestByCommon(Constants.BASE_URL + Constants.POST_MY_MESSAGE_URL, infos, MyHttp.POST, MyWorkActivity.this, false, null, new SimplePaserJsonCallback() {

            @Override
            public void onVerifyIsNull() {
                mHandler.sendEmptyMessage(WORK_INFO);
            }

            @Override
            public void onVerifySuccess(String dataRaw, boolean isCache) {
            }

        });
    }

    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        switch (msg.what) {
            case REFRESH_LIST:
                if (lists.size() > 0){
                    mLayoutEmpty.setVisibility(View.GONE);
                    mListView.setEnablePullDown(true);
                }else{
                    mLayoutEmpty.setVisibility(View.VISIBLE);
                    mListView.setEnablePullDown(false);
                }
                adapter.notifyDataSetChanged();
                break;
        }
    }

    @Override
    public boolean getIsNeedLogin() {
        return true;
    }

    /**
     * ListView的Adapter
     */
    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return lists.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int i, View convertView, ViewGroup viewGroup) {

            ViewHolder holder = null;

            if (convertView == null) {
                convertView = View.inflate(MyWorkActivity.this, R.layout.item_my_message, null);
                holder = new ViewHolder();
                holder.icon = (ImageView) convertView.findViewById(R.id.iv_item_msg_icon);
                holder.redPoint = (ImageView) convertView.findViewById(R.id.iv_item_msg_point);
                holder.title = (TextView) convertView.findViewById(R.id.tv_item_msg_title);
                holder.content = (TextView) convertView.findViewById(R.id.tv_item_msg_content);
                holder.workState = (TextView) convertView.findViewById(R.id.tv_work_state);
                holder.line = convertView.findViewById(R.id.work_line) ;

                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            WorkInfo info = lists.get(i);

            if (i == 0){
                holder.line.setVisibility(View.GONE);
            }

            //处理红点的显示
            if (info.isread == 0) {
                holder.redPoint.setVisibility(View.VISIBLE);
            } else {
                holder.redPoint.setVisibility(View.INVISIBLE);
            }

            holder.workState.setVisibility(View.VISIBLE);
            if (info.status == TO_AUDIT){
                //待审核
                holder.workState.setText(R.string.to_audio);
            }else if (info.status == AUDIT_COMPLETED){
                //审核完成
                holder.workState.setText(R.string.audit_completed);
            }

            holder.title.setText(info.title);
            holder.content.setText(info.publishtime);
            holder.icon.setImageResource(R.drawable.complain_default_pic);
            if (info.picurls != null && info.picurls.size() > 0) {
                bitmapUtils.display(holder.icon, info.picurls.get(0).smallpic);
            }

            return convertView;
        }
    }

    private class ViewHolder {
        ImageView icon;
        ImageView redPoint;
        TextView title;
        TextView content;
        View line;
        TextView workState;
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadData(1 , "" , LOAD_NORMAL);
    }

    /**
     * 展示长按删除的dialog
     */
    private void showDeleteDialog(final int position) {

        final int newPosition = position -1;
        DialogFactory.chooseDialog(MyWorkActivity.this, R.string.delete_task_des, R.string.sure, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //TODO 长按删除收藏的消息,暂时直接弹出框从集合删除
                Map<String, Object> maps = new HashMap<String, Object>();
                maps.put("id", lists.get(newPosition).msgid);
                MyHttp.requestByCommon(Constants.BASE_URL + Constants.POST_DELETE_MSG_URL, maps, MyHttp.POST, MyWorkActivity.this, false, null, new SimplePaserJsonCallback() {
                    @Override
                    public void onVerifyIsNull() {
                        lists.remove(newPosition);
                        mHandler.sendEmptyMessage(REFRESH_LIST);
                    }

                    @Override
                    public void onVerifySuccess(String dataRaw, boolean isCache) {

                    }

                    @Override
                    public void onErrorCodeError(BaseEntity.MyError mError) {
                        super.onErrorCodeError(mError);
                        DialogFactory.warningDialog(MyWorkActivity.this, mError.msg);
                    }
                });

            }
        });
    }
}
